﻿using System;
using System.Collections.Generic;
using TrueSync;
using TrueSync.Physics2D;
using Framework;

public class GuardAlarmRect : Fixture
{
    List<int> mCollidingEntityIDs;
    List<int> mLastCollidingEntityIDs;

    public GuardAlarmRect(Shape shape, TSVector2 position, FP rotation, object userdata = null) : base(shape, position, rotation, userdata)
    {
        mCollidingEntityIDs = new List<int>();
        CollisionCategories = Category.BodyHit;
        OnCollision = DoOnCollisionCallback;
    }

    void OnPreCollision()
    {
        mLastCollidingEntityIDs = mCollidingEntityIDs;
        mCollidingEntityIDs = new List<int>();
        for (int i = 0; i < mLastCollidingEntityIDs.Count; i++)
        {
            ObjHandle<LogicEntity> entity = GameManager.Instance.GetEntity(mLastCollidingEntityIDs[i]);
            if (entity.IsValid && entity.handle is FightCharacter)
            {
                entity.handle.GetLogicComponent<LogicStateMachineComponent>().IsTouchingRivalsGuardAlarmRect = false;
            }
        }
    }

    void DoOnCollisionCallback(Fixture myFixture, Fixture otherFixture)
    {
        ObjHandle<LogicEntity> myEntity = (ObjHandle<LogicEntity>)myFixture.UserData;
        ObjHandle<LogicEntity> otherEntity = (ObjHandle<LogicEntity>)otherFixture.UserData;
        //自己或者自己发出的东西过滤
        if (otherEntity.IsValid == false || otherEntity.handle.PlayerID == myEntity.handle.PlayerID)
            return;
        if (mCollidingEntityIDs.Contains(otherEntity.handle.EntityID) == false)
            mCollidingEntityIDs.Add(otherEntity.handle.EntityID);
    }

    public void OnPostCollision()
    {
        for (int i = 0; i < mCollidingEntityIDs.Count; i++)
        {
            ObjHandle<LogicEntity> entity = GameManager.Instance.GetEntity(mCollidingEntityIDs[i]);
            if (entity.IsValid && entity.handle is FightCharacter)
            {
                entity.handle.GetLogicComponent<LogicStateMachineComponent>().IsTouchingRivalsGuardAlarmRect = true;
            }
        }
    }

    public override void OnDestroy()
    {
        mCollidingEntityIDs.Clear();
        base.OnDestroy();
    }

    public override void OnAddToWorld(CollisionWorld world)
    {
        base.OnAddToWorld(world);
        world.OnPreCollision += OnPreCollision;
        world.OnPostCollision += OnPostCollision;
    }

    public override void OnRemoveFromWorld(CollisionWorld world)
    {
        base.OnRemoveFromWorld(world);
        world.OnPreCollision -= OnPreCollision;
        world.OnPostCollision -= OnPostCollision;
    }
}
